package com.example.zyfypt516wh.model;

import static com.example.zyfypt516wh.common.Common.BASEURL;

import com.example.zyfypt516wh.service.UserService;
import com.example.zyfypt516wh.bean.UserBean;
import com.example.zyfypt516wh.iface.LoginListener;
import com.example.zyfypt516wh.iface.LoginFace;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginModel implements LoginFace {

    private Retrofit retrofit;

    public LoginModel() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Override
    public void getLoginResult(String username, String pass, LoginListener loginListener) {
        //使用 Retrofit----2
        UserService userService
                = retrofit.create(UserService.class);
        Call<UserBean> call
                = userService.login(username, pass);
        //使用 Retrofit----3
        call.enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getId() != null) {
                    loginListener.onResponse(response.body());//登录成功
                    System.out.println("--登录成功： " + response.body().getSessionid());

                } else if (response.body().getError().contains("不正确")) {
                    loginListener.onFail(response.body().getError());//用户名密码错误
                    System.out.println("--登录失败： " + response.body().getError());
                } else {
                    loginListener.onFail("未知错误");//未知错误
                    System.out.println("--未知错误");
                }
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                loginListener.onFail(t.getMessage());
                //在 logcat 中查看错误原因 sout
                System.out.println("--网络错误： " + t.getMessage());
            }
        });
    }
}
